package mcom.xmks.bluetooth.mesh.base;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;

import mcom.xmks.bluetooth.mesh.dialog.UserDialog;
import mcom.xmks.bluetooth.mesh.utils.ToastUtil;

public abstract class AbstractActivity extends AppCompatActivity {
    /**将框架显示为子集*/
    private static final String EXTRA_SHOW_FRAGMENT_AS_SUBSETTING =":settings:show_fragment_as_subsetting";
    private AbstractActivity self = this;
    private   BleReceiver bleReceiver=null;
    /**请求返回码*/
    private final int requestCode=1110;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView();
        initWidget();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(bleReceiver!=null)
           unregisterReceiver(bleReceiver);
        bleReceiver=null;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==this.requestCode){
            boolean isManualPermission=false;  //手动权限
            String denied="";
            for(int i=0;i<permissions.length;i++) {
                int grantResult = grantResults[i];
                if(grantResult==PackageManager.PERMISSION_GRANTED){
                    Log.e("requestPermissions",permissions[i]+"权限被允许。");
                }else {
                   //呗禁用，应道用户到设置页面
                    isManualPermission=true;
                    if(denied.length()>0){
                        denied+=","+permissions[i];
                    }else{
                        denied=permissions[i];
                    }
                    Log.e("requestPermissions", permissions[i] + "权限被禁止，请在系统设置里面授权该权限。");
                }
            }
            if(isManualPermission){
                UserDialog dialog=new UserDialog(this, "权限请求",
                       denied + "权限请求被拒，需要在系统设置页开启这些权限。进入到系统设置页开启吗？",
                       new UserDialog.OnConfirmListener() {
                   @Override
                   public void onConfirm(DialogInterface dialog) {
                       dialog.dismiss();
                       Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                       intent.setData(Uri.fromParts("package" , getPackageName(),null));
                       intent.putExtra("type", "110");
                       intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                       //显示为子框架（子框架下标题栏会显示返回图标）
                       intent.putExtra(EXTRA_SHOW_FRAGMENT_AS_SUBSETTING,true);
                       intentActivityResultLauncher.launch(intent);
                   }
               });
                dialog.setConfirmTitle("是");
                dialog.setCancelTitle("否");
                dialog.show();
            }
        }
    }

    /**
     * 设置视图（在实现类里面和{@link #initWidget()}方法一起代替{@link #onCreate(Bundle)}回调）
     */
    protected abstract void setView();
    /**设置视图（在实现类里面和{@link #setView()}方法一起代替{@link #onCreate(Bundle)}回调）*/
    protected abstract void initWidget();
    /**
     * 蓝牙状态侦听器(当状态发生改变时触发)
     * @param stateON 开启蓝牙
     * @param isTurning 正在执行
     */
    protected void onBluetoothStateListener(boolean stateON,boolean isTurning) {}

    /**
     * 检查全部允许的权限
     * @return
     */
    public boolean checkPermissionsAllowed(){
        return checkSelfPermissions(getRuntimePermissions());
    }

    /**
     * 检查指定权限列表
     * @param permissions
     * @return
     */
    public boolean checkSelfPermissions(String ... permissions){
        for(String permission:permissions){
            if(this.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED){
                return false;
            }
        }
        return true;
    }
    public boolean requestPermissions(){
        return requestPermissions(getRuntimePermissions());
    }
    /**
     * 请求权限
     * @param permissions 权限列表
     */
    public boolean requestPermissions(String ... permissions){
        List<String> permissionList=new ArrayList<>();
        for(String permission:permissions){   //过滤被拒绝的权限
            if(this.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED){
                permissionList.add(permission);
            }
        }
        if(permissionList.size()>0) {
            String[] ps=  permissionList.toArray(new String[permissionList.size()]);
            this.requestPermissions(ps, requestCode);
            return true;
        }
        return false;
    }
    private final String[] getRuntimePermissions(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){
            return new String[]{Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN,
                    Manifest.permission.BLUETOOTH_ADVERTISE,Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION};
        }else{
            return new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
        }
    }
    /**
     * 是否支持BLE
     * @return
     */
    protected final boolean isSupportBle(){
        PackageManager packageManager = this.getPackageManager();
        return BluetoothAdapter.getDefaultAdapter() != null && packageManager != null && packageManager.hasSystemFeature(
                PackageManager.FEATURE_BLUETOOTH_LE
        );
    }
    /**
     * 蓝牙开启
     * @return
     */
    protected final boolean isBluetoothOpened(){
        return BluetoothAdapter.getDefaultAdapter()!=null && BluetoothAdapter.getDefaultAdapter().isEnabled();
    }

    /**
     * 打开蓝牙
     */
    protected void openBluetooth(){
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.S){
             if (requestPermissions(getRuntimePermissions()))
                 return;
        }
        intentActivityResultLauncher.launch(intent);
    }
    public final void  showToast(String message){
        runOnUiThread(() -> ToastUtil.create(self,message));
    }
    ActivityResultLauncher<Intent> intentActivityResultLauncher  = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK) {
                    showToast("接受请求");
                } else if(result.getResultCode()==RESULT_CANCELED){
                    showToast("取消请求");
                }
            });
    /*****************广播侦听***********************/
    /**
     * 注册蓝牙状态广播。用于接收蓝牙状态改变通知(仅在当前Activity有效)
     */
    public void registerBluetoothStateReceiver(){
        BluetoothAdapter bluetoothAdapter;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            android.bluetooth.BluetoothManager bluetoothManager=(android.bluetooth.BluetoothManager)
                    this.getSystemService(Context.BLUETOOTH_SERVICE);
            bluetoothAdapter=bluetoothManager.getAdapter();
        }else {
            bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        }
        if(bluetoothAdapter!=null) {
            IntentFilter filter = new IntentFilter();
            filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//蓝牙状态值发生改变
            bleReceiver=new BleReceiver();
            this.registerReceiver(bleReceiver, filter);//注册广播侦听
        }
    }
     class BleReceiver extends   BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { //蓝牙状态值发生改变
                final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
                switch (state) {
                    case BluetoothAdapter.STATE_OFF:
                        //蓝牙适配器已关闭。
                        onBluetoothStateListener(false,false);
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        //蓝牙适配器正在关闭。
                        onBluetoothStateListener(false,true);
                        break;
                    case BluetoothAdapter.STATE_ON:
                        //本地Bluetooth适配器已打开，可以使用。
                        onBluetoothStateListener(true,false);
                        break;
                    case BluetoothAdapter.STATE_TURNING_ON:
                        //本地Bluetooth适配器正在打开。
                        onBluetoothStateListener(true,true);
                        break;
                }
            }
        }
    };
}
